<template>
  <el-dialog class="dialog" :visible.sync="retrieveModal" width="40%" append-to-body>
    <div slot="title">
      <el-steps :active="activeStep" finish-status="success" simple>
        <el-step title="手机号验证"></el-step>
        <el-step title="密码重置"></el-step>
        <el-step title="重置完成"></el-step>
      </el-steps>
    </div>
    <div v-if="activeStep == 1">
      <el-form ref="form" :model="retrieveForm" :rules="retrieveRules" class="login-form">
        <el-form-item class="login-name" prop="phone">
          <el-input v-model="retrieveForm.phone" id="phone" type="text" auto-complete="off" placeholder="请输入手机号">
            <svg-icon slot="prefix" icon-class="userdx" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="retrieveForm.code" auto-complete="off" placeholder="短信验证码" style="width: 62%;margin-right: 15px;">
            <svg-icon slot="prefix" icon-class="validCodedx" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <el-button type="primary" @click="sendCode(retrieveForm.phone)" :disabled="sendCodeObj.disabled">{{sendCodeObj.textContent}}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="activeStep == 2">
      <el-form ref="passwordForm" :model="passwordForm" :rules="passwordFormRules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item prop="password" style="margin-bottom:44px">
              <template slot="label">新密码</template>
              <el-input v-model="passwordForm.password" show-password placeholder="请输入新密码" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="确认密码" prop="passwordCheck">
              <el-input v-model="passwordForm.passwordCheck" show-password placeholder="请确认新密码" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div v-if="activeStep == 3">
      <div class="success-tip">
        <i class="el-icon-success"></i>修改成功
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleNext">{{activeStep == 3?"关闭":"下一步"}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { sendCode } from "../../../api/commonApi";
import { loginByMsg, resetPwdByToken } from '../../../api/login'
import { isCheckPosswordStrength } from "../../../utils/validate";
export default {
  data()
  {
    let validatePass2 = (rule, value, callback) =>
    {
      if (value === '')
      {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.passwordForm.password)
      {
        callback(new Error('两次输入密码不一致!'));
      } else
      {
        callback();
      }
    };

    let validatePass = (rule, value, callback) => 
    {
      if (value === '')
      {
        callback(new Error('请输入密码'));
      }
      else 
      {
        let checkReturnObj = isCheckPosswordStrength(value, this.DICT_PASSWORD_STRENDTH, this.notAllowKey);
        if (checkReturnObj.isOk)
        {
          callback();
        }
        else
        {
          callback(new Error(checkReturnObj.msg));
        }
      }
    }

    return {
      token: null,
      //短信发送信息
      sendCodeObj: {
        timgerId: null,
        disabled: false,
        countdown: 60,
        textContent: "发送验证码"
      },
      retrieveModal: false,
      activeStep: 1,
      retrieveForm: {
        phone: '',
        code: ''
      },
      retrieveRules: {
        phone: [
          { required: true, message: '手机号必填', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      //密码不允许包含的字符串
      notAllowKey: [],
      //密码表单
      passwordForm: {
        password: null,
        passwordCheck: null
      },
      //密码表单检验规则
      passwordFormRules: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass, trigger: 'blur' }
        ],
        passwordCheck: [
          { required: true, message: "请再次输入密码", trigger: "blur" },
          { validator: validatePass2, trigger: 'blur' }
        ],
      }
    }
  },
  computed: {
    ...mapState("dict", ["DICT_PASSWORD_STRENDTH"]),
  },
  created()
  {
    //获取办理方式列表
    this.getCs({
      dictKey: "DICT_PASSWORD_STRENDTH",
      code: "xtsz_password_strendth"
    })
  },
  methods: {
    ...mapActions("dict", ["getCs"]),
    init()
    {
      this.token = null;
      this.passwordForm = {
        password: null,
        passwordCheck: null
      }
      this.retrieveForm = {
        phone: '',
        code: ''
      }
    },
    handleNext()
    {
      if (this.activeStep == 1)
      {
        this.$refs.form.validate(valid =>
        {
          if (valid)
          {
            //验证码登录获取token
            loginByMsg({
              phone: this.retrieveForm.phone,
              code: this.retrieveForm.code
            }).then(res =>
            {
              this.token = res.token || null;
              if (this.token)
              {
                this.activeStep++;
              }
            }).catch(error =>
            {
              this.$message.error(error.data?.message);
            })
          }
        })
      }
      else if (this.activeStep == 2)
      {
        this.$refs.passwordForm.validate(valid =>
        {
          if (valid)
          {
            resetPwdByToken({
              token: this.token,
              password: this.passwordForm.password
            }).then(res =>
            {
              this.activeStep++;
            })
          }
        })
      }
      else if (this.activeStep == 3)
      {
        this.retrieveModal = false;
        this.init();
      }
    },
    show()
    {
      this.retrieveModal = true
    },
    //开启短信验证码倒计时
    countDowm()
    {
      // 禁用按钮，防止重复点击  
      this.sendCodeObj.disabled = true;
      if (this.sendCodeObj.timgerId)
      {
        clearInterval(this.sendCodeObj.timgerId);
      }
      // 开始倒计时  
      this.sendCodeObj.timgerId = setInterval(() =>
      {
        this.sendCodeObj.countdown--;
        // 更改按钮文本为"重新发送"  
        this.sendCodeObj.textContent = '重新发送(' + this.sendCodeObj.countdown + 's)';
        if (this.sendCodeObj.countdown <= 0)
        {
          // 倒计时结束，重置按钮状态  
          this.sendCodeObj.disabled = false;
          this.sendCodeObj.textContent = '发送验证码';
          this.sendCodeObj.countdown = 60;
          clearInterval(this.sendCodeObj.timgerId);
        }
      }, 1000);
    },
    //发送短信验证码
    sendCode(P_Phone)
    {
      if (P_Phone)
      {
        if (!this.sendCodeObj.disabled)
        {
          sendCode({
            phone: P_Phone
          }).then(res =>
          {
            //开启倒计时
            this.countDowm();
          }).catch(err =>
          {
            this.countDowm();
          })
        }
      }
      else
      {
        this.showError("请输入手机号")
      }
    },
  }
}
</script>

<style scoped lang="scss">
.dialog ::v-deep .el-dialog__header .el-dialog__headerbtn {
  top: 5px;
  right: 5px;
}
.login-form {
  width: 60%;
  margin: 0 auto;
  text-align: center;
  padding: 25px 0;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
}
.success-tip {
  height: 200px;
  color: #67c23a;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>